from rest_framework.exceptions import NotFound
from rest_framework_simplejwt.tokens import RefreshToken

from account.models import User
from permissions.services import PermissionService


class AccountService:

    def __init__(self, username='', user=None):
        if user is not None:
            self.user = user
        else:
            user = User.objects.filter(username=username)
            if user.count() == 0:
                raise NotFound('用户不存在')
            self.user = user.last()

    @staticmethod
    def flush_expired_tokens():
        from django.core.management import execute_from_command_line
        execute_from_command_line(['manage.py', 'flushexpiredtokens'])

    def get_token(self):
        token_class = RefreshToken
        refresh = token_class.for_user(self.user)
        access = getattr(refresh, 'access_token')
        ret = {
            'access': str(access),
            'refresh': str(refresh)
        }
        return ret

    def get_dict_type_permissions(self):

        return PermissionService.get_dict_type_permissions(self.user)
